package com.itheima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.article.feign.ApAuthorFeign;
import com.itheima.article.pojo.ApAuthor;
import com.itheima.common.constants.BusinessConstants;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.vo.PageResultVo;
import com.itheima.common.vo.ResultVo;
import com.itheima.user.dto.ApUserRealnamePageRequestDto;
import com.itheima.user.mapper.ApUserMapper;
import com.itheima.user.pojo.ApUser;
import com.itheima.user.pojo.ApUserRealname;
import com.itheima.user.mapper.ApUserRealnameMapper;
import com.itheima.user.service.ApUserRealnameService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.wemedia.feign.WmUserFeign;
import com.itheima.wemedia.pojo.WmUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * @description <p>APP实名认证信息 业务实现</p>
 *
 * @version 1.0
 * @package com.itheima.user.service.impl
 */
@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    @Autowired
    private ApUserMapper apUserMapper;

    @Autowired
    private WmUserFeign wmUserFeign;

    @Autowired
    private ApAuthorFeign apAuthorFeign;

    /**
     * 实名认证分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageResultVo pageList(ApUserRealnamePageRequestDto dto) {
        //1. 设置分页参数
        IPage<ApUserRealname> pageInfo = new Page<>(dto.getPage(), dto.getSize());
        //2. 构建查询条件
        LambdaQueryWrapper<ApUserRealname> lqw = new LambdaQueryWrapper<>();
        lqw.eq(null != dto.getStatus(), ApUserRealname::getStatus, dto.getStatus());
        //3. 查询
        page(pageInfo, lqw);
        //4. 构建返回结果
        return PageResultVo.pageResult(dto.getPage(), dto.getSize(), pageInfo.getTotal(), pageInfo.getRecords());
    }

    /**
     * 审核-驳回
     *
     * @param paramMap
     */
    @Override
    public void authFail(Map<String, Object> paramMap) {
        //1. 获取参数
        Integer id = (Integer) paramMap.get("id");
        String reason = (String) paramMap.get("msg");
        //2. 参数校验, 忽略

        //3. 更新
        ApUserRealname apUserRealname = new ApUserRealname();
        apUserRealname.setId(id.longValue());
        apUserRealname.setReason(reason);
        apUserRealname.setStatus(BusinessConstants.ApUserRealnameConstants.AUTH_REJECT);
        apUserRealname.setUpdatedTime(LocalDateTime.now());
        // 使用了mybatis plus的更新方法，特点：属性有值才会更新。
        updateById(apUserRealname);
    }

    /**
     * 审核-通过
     *
     * @param paramMap
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void authPass(Map<String, Object> paramMap) {
        //取出参数
        Integer id = (Integer) paramMap.get("id");
        //1. leadnews_user.ap_user_realname
        //   通过id查询 得到user_id
        ApUserRealname apUserRealname = getById(id);

        //2. leadnews_user.ap_user表
        //   通过user_id查询ap_user表，得到apUser
        Long apUserId = apUserRealname.getUserId();
        ApUser apUser = apUserMapper.selectById(apUserId);

        //3. 创建自媒体人信息
        Long wmUserId = addWmUser(apUser);
        //4. 有自媒体人后，才能来创建作者
        addApAuthor(apUser, wmUserId);

        //更新实名认证状态
        updateRealnameStatus(id);

        // 更新用户认证信息
        updateApUser(apUserId);
    }

    /**
     * 更新用户实名认证信息
     * @param apUserId
     */
    private void updateApUser(Long apUserId) {
        //   更新
        ApUser updateApUser = new ApUser();
        //      is_identify_authenticated=1
        updateApUser.setIsIdentityAuthentication(BusinessConstants.ApUserConstants.AUTHENTICATED);
        //      flag=1
        updateApUser.setFlag(BusinessConstants.ApUserConstants.FLAG_WEMEDIA);
        updateApUser.setId(apUserId);
        apUserMapper.updateById(updateApUser);
    }

    /**
     * 更新实名认证状态
     * @param id
     */
    private void updateRealnameStatus(Integer id) {
        //   通过id更新
        ApUserRealname updateApUserRealname = new ApUserRealname();
        //      status=9
        updateApUserRealname.setStatus(BusinessConstants.ApUserRealnameConstants.AUTH_PASS);
        //      update_time=now
        updateApUserRealname.setUpdatedTime(LocalDateTime.now());
        updateApUserRealname.setId(id.longValue());
        updateById(updateApUserRealname);
    }

    /**
     * 添加作者信息
     * @param apUser
     * @param wmUserId
     */
    private void addApAuthor(ApUser apUser, Long wmUserId) {
        //   先查询通过wm_user_id(wmUser.id)和user_id(apUser.id)查询是否存在
        ResultVo<ApAuthor> getResult = apAuthorFeign.getByApUserIdWmUserId(apUser.getId(), wmUserId);
        if(!getResult.isSuccess()){
            log.error("远程调用自文章微服查询作者信息失败!apUserId="+apUser.getId() + ",wmUserId=" + wmUserId);
            throw new LeadNewsException("远程调用自媒体查询信息失败!");
        }
        ApAuthor apAuthor = getResult.getData();
        //   不存在，则添加ap_author
        if(null == apAuthor) {
            apAuthor = new ApAuthor();
            apAuthor.setName(apUser.getName());
            apAuthor.setType(BusinessConstants.ApAuthorConstants.A_MEDIA_USER);
            apAuthor.setUserId(apUser.getId());
            apAuthor.setWmUserId(wmUserId);
            apAuthor.setCreatedTime(LocalDateTime.now());
            //远程调用添加作者
            ResultVo addResult = apAuthorFeign.add(apAuthor);
            //   出错则要抛异常
            if(!addResult.isSuccess()){
                // 如果失败则要抛异常，触发主业务回滚
                log.error("远程调用自文章微服添加作者信息失败!apUserId="+apUser.getId()  + ",wmUserId=" + wmUserId);
                throw new LeadNewsException("远程调用自文章微服添加作者信息失败!");
            }
        }
    }

    /**
     * 添加自媒体人
     * @param apUser
     * @return
     */
    private Long addWmUser(ApUser apUser) {
        //1. 先查询通过ap_user_id查询是否存在
        ResultVo<WmUser> getByApUserIdResult = wmUserFeign.getByApUserId(apUser.getId());
        if (!getByApUserIdResult.isSuccess()) {
            // 不成功
            log.error("远程调用自媒体查询自媒体信息失败!apUserId="+apUser.getId());
            throw new LeadNewsException("远程调用自媒体查询信息失败!");
        }
        WmUser wmUser = getByApUserIdResult.getData();
        //2. 不存在，则添加wm_user  wmUser
        if(null == wmUser) {
            //2.1 复制apUser属性值到wm_user
            // 创建pojo，给pojo属性赋值
            wmUser = new WmUser();
            //把参数1属性值复制给参数2，参数不能为null，属性名与属性类型必须一致
            BeanUtils.copyProperties(apUser, wmUser);
            wmUser.setId(null);// id不一样，不能复制, 自媒体端自己自动生成
            wmUser.setApUserId(apUser.getId());
            wmUser.setNickname(apUser.getName());
            wmUser.setStatus(BusinessConstants.WmUserConstants.STATUS_OK);
            wmUser.setType(BusinessConstants.WmUserConstants.TYPE_PERSONAL);
            wmUser.setScore(0);//分数为0
            wmUser.setCreatedTime(LocalDateTime.now());
            // 远程调用添加
            ResultVo<WmUser> addResult = wmUserFeign.add(wmUser);
            // 判断调用的结果是否成功
            if (!addResult.isSuccess()) {
                // 如果失败则要抛异常，触发主业务回滚
                log.error("远程调用自媒体添加自媒体账号信息失败!apUserId="+apUser.getId());
                throw new LeadNewsException("远程调用自媒体添加自媒体账号信息失败!");
            }
            // 为什么多这一行代码??
            wmUser = addResult.getData();
        }//存在则不用重复添加了
        return wmUser.getId();
    }
}
